package com.elm_springboot_s.service.impl;

import com.elm_springboot_s.mapper.UserMapper;
import com.elm_springboot_s.pojo.User;
import com.elm_springboot_s.service.UserService;
import com.elm_springboot_s.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public User getUserByNameAndPass(String userName, String password) {
        return userMapper.getUserByNameAndPass(userName, password);
    }

    @Override
    public User getUserByName(String userName) {
        return userMapper.getUserByName(userName);
    }

    @Override
    public int saveUser(String userName, String password, Integer userSex) {
        User existingUser = getUserByName(userName);
        if (existingUser != null) {
            return 0;
        }
        
        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        user.setUserSex(userSex);
        return userMapper.saveUser(user);
    }

    @Override
    public String login(String userName, String password) {
        User user = getUserByNameAndPass(userName, password);
        if (user == null) {
            return null;
        }

        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getUserId());
        claims.put("userName", user.getUserName());
        String token = JwtUtil.genToken(claims);

        stringRedisTemplate.opsForValue().set(token, token, 12, TimeUnit.HOURS);

        return token;
    }
} 